package com.lst.servlet;

import java.io.File;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.common.CommFun;
import com.lst.dao.ResourcesMapper;
import com.lst.entity.request.DynamicReqPara;
import com.lst.model.Dynamic;
import com.lst.model.Resources;
import com.lst.service.DynamicService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;
import com.lst.utils.SensitiveUtil;


/**
 * @ClassName: DynamicAddServlet
 * @Description: 动态发布接口
 * 
 */
public class DynamicAddServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private DynamicService dynamicService = ctx.getBean(DynamicService.class);
	private ResourcesMapper resourcesMapper = ctx.getBean(ResourcesMapper.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		BaseResponse resPara = new BaseResponse();

		try {
			DynamicReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
			Integer userid = Integer.valueOf(reqPara.getUserid());
			Integer dynamicType = Integer.valueOf(reqPara.getDynamicType());
			Integer recordId = StringUtils.isEmpty(reqPara.getRecordId())?0:Integer.valueOf(reqPara.getRecordId());
			String content = reqPara.getContent();
			String dynamicUrl = reqPara.getDynamicUrl();
//			String str1=SensitiveUtil.check(content);
//			 if(str1.length()==2 || str1==""){
				 String pictureUrl = "";
					if(!StringUtils.isEmpty(dynamicUrl)){
						List<String> urls = dealImgs(dynamicUrl, startDate, userid);
						pictureUrl = urls.get(0);
						if(urls!=null&&urls.size()>0){
							for(int i=1;i<urls.size();i++){
								pictureUrl=pictureUrl+","+urls.get(i);
							}
						}
						
					}
					Dynamic md = new Dynamic();
					
					md.setCreateuser(userid);
					md.setContent(content);
					md.setDynamicType(dynamicType);
					md.setDynamicUrl(pictureUrl);
					md.setCreatedate(startDate);
					md.setIsDeleted(false);
					md.setRecordId(recordId);
					
					dynamicService.insert(md);
					
					resPara.setCode(CommCode.M_Y000000);
					resPara.setMessage(CommCode.M_Y000001); 
//			 }else{
//				 resPara.setCode(CommCode.M_A000000);
//				 resPara.setMessage("描述里含有违禁词，请修改");
//			 }
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
	//		logger.info("DynamicAddServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

	//		logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public DynamicReqPara getReqPara(HttpServletRequest request) {

		DynamicReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new DynamicReqPara());

			reqPara = (DynamicReqPara) baseRequest.clone();

			String dynamicType = request.getParameter("dynamicType");
			String dynamicUrl = request.getParameter("dynamicUrl");
			String content = request.getParameter("content");
			String userid = request.getParameter("userid");
			String recordId = request.getParameter("recordId");

//			logger.info("reqPara dynamicType: " + dynamicType);
//			logger.info("reqPara dynamicUrl: " + dynamicUrl);
//			logger.info("reqPara content:" + content);
//			logger.info("reqPara userid:" + userid);
//			logger.info("reqPara recordId:" + recordId);

	        reqPara.setDynamicType(dynamicType);
	        reqPara.setDynamicUrl(dynamicUrl);
	        reqPara.setContent(content);
	        reqPara.setUserid(userid);
            reqPara.setRecordId(recordId);
		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		DynamicReqPara cdReqPara = (DynamicReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

	    if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		} else {
			flag = true;
		}

		return  flag;
	}
	
	/**
	 * 
	 * @Title: dealImgs
	 * @Description: 处理图片集 
	 * @param @param portrait  
	 * @param @param startDate
	 * @param @param mstClient
	 * @param @return
	 * @param @throws ParseException    设定文件
	 * @return List<String>    返回类型
	 */
	private synchronized List<String> dealImgs(String portrait,Date startDate,Integer userId) throws ParseException{
		//以逗号分分割多张图片
		String [] portraits = portrait.split(",");
		//存放“文件夹 + 图片名称”集
		List<String> urls = new ArrayList<String>();
		//图片资源集
		List<Resources> mstResources = new ArrayList<Resources>();
		//获取时分秒文件夹地址
		String timeAddr = DateUtil.getCurrentTime(DateUtil.ALL_DATE_HORIZONTAL);
		//获取工厂地址
		String facAddr = CommonUtils.getImg_file_path_linux() + timeAddr;

		// 创建工厂文件
		File facFile = new File(facAddr);
		if (!facFile.exists()) {
			facFile.mkdirs();
		}

		String imgName = "";// 图片名称
		String absPath = "";//文件绝对路径
		String relPath = "";//文件相对路径

		// 批量保存图片
		int len = portraits.length;
		for (int i = 0; i < len; i++) {

			imgName = DateUtil
					.getCurrentTime(DateUtil.ALL_DATETIME_STRING_QUEUE)
					+ i;

			absPath = facAddr + "/"+ imgName;

			CommFun.base64StringToImage4One2(
					portraits[i], absPath);

			relPath = CommCode.RESOURCE_URL_IMAGE + timeAddr +"/"+imgName + ".jpg";
			urls.add(relPath);

			Resources resource = new Resources();
			resource.setCreatedate(startDate);
			resource.setCreateuser(userId);
			resource.setEnabled(true);
			resource.setExtname(".jpg");
			resource.setIsdeleted(false);
			resource.setResname(imgName);
			resource.setRespath(CommCode.RESOURCE_URL_IMAGE + timeAddr +"/");
			resource.setOrderindex(i);
			resource.setOwnerid(userId);
			resource.setOwnertablename("MST_CLIENT");
			resource.setRestype(CommCode.SYSCODE_REOURCES_TYPE_IMAGE);

			mstResources.add(resource);

			logger.info("decPara absPath : " + absPath + "and the index :" + i);
			logger.info("decPara relPath : " + relPath + "and the index :" + i);
		}

		resourcesMapper.saveList(mstResources);

		return urls;

	}

}
